<template>
  <div class="wrapper">
    <div class="main">
      <h2>发布新攻略</h2>
      <p class="desc">分享你的个人游记，让更多人看到哦！</p>
      <div class="form">
        <el-form ref="form" :model="form">
          <el-form-item>
            <el-input
              placeholder="请输入标题"
              clearable
              v-model="form.title"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <!-- 只在客户端渲染 -->
            <client-only>
              <vue-editor
                v-model="form.content"
                :editorToolbar="customToolbar"
                :useCustomImageHandler="true"
                @image-added="imgUpload"
              />
            </client-only>
          </el-form-item>
          <el-form-item>
            <span class="tis_text">选择城市</span>
            <el-autocomplete
              :trigger-on-focus="false"
              :highlight-first-item="true"
              v-model="form.city"
              :fetch-suggestions="queryCitySearch"
              placeholder="请搜索游玩城市"
              class="el-autocomplete"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">发布</el-button>
            <span class="or_text">或者</span>
            <span class="on_save" @click="handleSave">保存到草稿</span>
          </el-form-item>
        </el-form>
        <!-- 未登录弹出框 -->
        <div>
          <el-dialog
            title="请先登录或注册"
            width="30%"
            :visible.sync="dialogVisible"
          >
            <span>
              <Dialog @closeDialog="closeDialog" />
            </span>
          </el-dialog>
        </div>
      </div>
    </div>
    <div class="aside">
      <Drafts @reEdit="reEdit" />
    </div>
  </div>
</template>

<script>
import moment from "moment";
export default {
  data() {
    return {
      dialogVisible: false,
      // 富文本编辑器的自定义工具栏
      customToolbar: [
        ["bold", "italic", "underline", "strike"],
        [{ header: [false, 1, 2] }],
        ["image"],
      ],
      form: {
        title: "",
        content: "",
        city: "",
      },
    };
  },
  created() {
    // 如果地址栏有城市名，默认把搜索到的第一个城市名填上去
    if (this.$route.query.city) {
      this.$axios({
        url: "/airs/city",
        params: {
          name: this.$route.query.city,
        },
      }).then((res) => {
        if (res.data.data[0].name) {
          this.form.city = res.data.data[0].name;
        }
      });
    }
  },
  methods: {
    // 关闭弹出框
    closeDialog() {
      this.dialogVisible = false;
    },
    open(message) {
      this.$alert(message, "提示", {
        confirmButtonText: "确定",
        type: "warning",
      });
    },
    // 发布文章
    onSubmit() {
      console.log(this.form);
      // 各内容不能为空
      if (!this.form.title) {
        this.open("请填写标题");
        return;
      }
      if (!this.form.content) {
        this.open("请输入内容");
        return;
      }
      if (!this.form.city) {
        this.open("请选择城市");
        return;
      }
      // 判断用户是否登录
      if (!this.$store.state.user.userInfo.token) {
        this.dialogVisible = true;
        return;
      }

      // 发布文章请求
      this.$axios({
        method: "post",
        url: "/posts",
        data: this.form,
        headers: {
          Authorization: "Bearer " + this.$store.state.user.userInfo.token,
        },
      }).then((res) => {
        console.log(res);
        if (res.data.message === "新增成功") {
          this.$message.closeAll();
          this.$message.success("发布成功");
          this.$router.push(`/post?city=${this.form.city}`);
          this.form = {
            title: "",
            content: "",
            city: "",
          };
        }
      });
    },
    // 保存到草稿箱
    handleSave() {
      if (!this.form.title && !this.form.content && !this.form.city) {
        this.$message.closeAll();
        this.$message.warning("至少有一项不能为空才能保存哦~~");
        return;
      }
      const time = moment().format("yyyy-MM-DD");
      const data = { ...this.form, time };
      this.$store.commit("post/addDraft", data);

      this.$message.success("已经存到草稿箱啦~~");
      this.form = {
        title: "",
        content: "",
        city: "",
      };
    },
    //  草稿箱的重新编辑
    reEdit(index) {
      const { time, ...data } = this.$store.state.post.posts[index];
      this.form = data;
    },

    // 加载城市
    loadCityList(queryString, showList) {
      // 远程服务器获取城市列表
      this.$axios({
        url: "/airs/city",
        params: {
          name: queryString,
        },
      }).then((res) => {
        console.log(res);
        const data = res.data.data.map((city) => {
          return {
            ...city,
            value: city.name,
          };
        });
        showList(data);
        // 保存第一项
        if (res.data.data[0].name) {
          this.form.city = res.data.data[0].name;
        }
      });
    },
    // 显示搜索建议
    queryCitySearch(queryString, showList) {
      this.loadCityList(queryString, showList);
    },

    // 富文本图片上传处理
    imgUpload(file, Editor, cursorLocation, resetUploader) {
      let data = new FormData();
      data.append("files", file);

      this.$axios({
        method: "post",
        url: "/upload",
        data,
      }).then((res) => {
        const url = this.$axios.defaults.baseURL + res.data[0].url;
        Editor.insertEmbed(cursorLocation, "image", url);
        resetUploader();
      });
    },
  },
};
</script>

<style lang="less" scoped>
.wrapper {
  width: 1000px;
  margin: 20px auto;
  display: flex;
  justify-content: space-between;
  .main {
    width: 750px;
    h2 {
      font-size: 22px;
      font-weight: 400;
    }
    .desc {
      font-size: 12px;
      color: #999;
      margin: 10px 0;
    }
    .tis_text {
      padding-right: 10px;
      font-size: 14px;
    }
    .or_text {
      font-size: 14px;
      margin-left: 14px;
    }
    .on_save {
      font-size: 14px;
      color: orange;
      cursor: pointer;
      &:hover {
        text-decoration: underline;
      }
    }
  }
  .aside {
    width: 225px;
  }
}
/deep/.quillWrapper {
  background-color: #fff;
  .ql-toolbar {
    line-height: 1;
  }
  .ql-editor {
    height: 400px;
    img {
      width: 100px;
      height: 100px;
      object-fit: cover;
    }
  }
}
</style>